#include "esp_vfs_fat.h"
#include "my_simple_sd.h"

static const char *mount_point = "/sdcard";

SDCard &SD = SDCard::GetInstance();

esp_err_t SDCard::init(int pin_MISO, int pin_MOSI, int pin_CLK, int pin_CS)
{
    sdmmc_host_t host = SDSPI_HOST_DEFAULT();
    host.slot = SPI2_HOST;
    spi_bus_config_t bus_cnf = {
        .mosi_io_num = pin_MOSI,
        .miso_io_num = pin_MISO,
        .sclk_io_num = pin_CLK,
        .quadwp_io_num = -1, // 这行不能省略
        .quadhd_io_num = -1, // 这行不能省略
        .max_transfer_sz = 400000,
    };
    spi_bus_initialize((spi_host_device_t)host.slot, &bus_cnf, SPI_DMA_CH_AUTO);
    static sdspi_device_config_t slot_cnf = {
        .host_id = SPI2_HOST,
        .gpio_cs = (gpio_num_t)pin_CS,
        .gpio_cd = SDSPI_SLOT_NO_CD, // 这行不能省略
        .gpio_wp = GPIO_NUM_NC,      // 这行不能省略
        .gpio_int = GPIO_NUM_NC,     // 这行不能省略
    };
    sdmmc_card_t *card;
    esp_vfs_fat_sdmmc_mount_config_t mount_cnf = {
        .format_if_mount_failed = false,
        .max_files = 5,
        .allocation_unit_size = 16 * 1024,
    };
    return esp_vfs_fat_sdspi_mount(mount_point, &host, &slot_cnf, &mount_cnf, &card);
}
FILE *SDCard::open(const std::string &path, const std::string &method)
{
    if (path[0] == '/')
        return fopen((std::string(mount_point) + path).c_str(), method.c_str());
    else
        return fopen((std::string(mount_point) + "/" + path).c_str(), method.c_str());
}
